from django.shortcuts import render
from django.views import View
from django.http import JsonResponse
from django.contrib import auth
import jwt
import time
from JWTDemo.settings import SECRET_KEY


class Auth(object):
    @staticmethod
    def encode_auth_token(username, exptime):
        now = int(time.time())
        payload = {'exp': now + exptime, 'iat': now, 'iss': SECRET_KEY,
                   'data': {'username': username}}
        return jwt.encode(payload, 'secret', algorithm='HS256')

    @staticmethod
    def decode_auth_token(auth_token):
        try:
            payload = jwt.decode(auth_token, 'secret', issuer=SECRET_KEY, algorithms=['HS256'])
            if 'data' in payload and 'username' in payload['data']:
                return payload
            else:
                return "非法的Token"
        except jwt.ExpiredSignatureError:
            return "Token过期"
        except jwt.InvalidTokenError:
            return "无效的Token"

    @staticmethod
    def identify(request):
        auth_header = request.headers.get('token')
        if auth_header:
            payload = Auth().decode_auth_token(auth_header)
            if isinstance(payload, dict):
                if payload["exp"] <= time.time():
                    result = "token已过期!"
                else:
                    result = payload["data"]
            else:
                result = payload
        else:
            result = '没有提供认证token'
        return result


class Index(View):
    def get(self, request, *args, **kwargs):
        return render(request, "index.html")

    def post(self, request, *args, **kwargs):
        datas = {"code": 1, "msg": ""}
        tk = Auth().identify(request)
        if isinstance(tk, dict):
            datas["code"] = 0
            datas["msg"] = tk["username"]
        else:
            datas["msg"] = tk
        return JsonResponse(datas)


class Login(View):
    def get(self, request, *args, **kwargs):
        return render(request, "login.html")

    def post(self, request, *args, **kwargs):
        datas = {"code": 1, "msg": ""}
        username = request.POST.get('username', '')
        password = request.POST.get('pwd', '')
        user = auth.authenticate(username=username, password=password)
        if user:
            datas["code"] = 0
            datas["msg"] = Auth().encode_auth_token(username, 60)  # 传入需要的参数的过期时间(秒)
        else:
            datas["msg"] = "用户名或者密码错误"
        return JsonResponse(datas)
